﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace CommonEngine
{
    /// <summary>
    /// 用于迭代XML的取值容器
    /// </summary>
    public sealed class XNodeC
    {
        public string LocalName { get; set; }
        public string Value { get; set; }

        public List<XNodeC> Elements { get; set; }

        /// <summary>
        /// 构造
        /// </summary>
        public XNodeC()
        {
            this.Elements = new List<XNodeC>();
        }

        public List<XNodeC> SelectXNode(string LName)
        {
            if (string.IsNullOrEmpty(LName))
                return null;

            List<XNodeC> Ls = new List<XNodeC>();
            if (this.LocalName == LName)
                Ls.Add(this);
            else
            {
                var Temp = SelectLs(this.Elements, LName);
                if (Temp != null)
                    Ls.AddRange(Temp);
            }

            return Ls;
        }
        private List<XNodeC> SelectLs(List<XNodeC> Ls, string LName)
        {
            if (string.IsNullOrEmpty(LName))
                return null;

            if (Ls == null || Ls.Count < 1)
                return null;

            List<XNodeC> pool = new List<XNodeC>();
            foreach (var v in Ls)
            {
                if (v.LocalName == LName)
                    pool.Add(v);
                else
                {
                    var Temp = SelectLs(v.Elements, LName);
                    if (Temp != null)
                        pool.AddRange(Temp);
                }
            }
            return pool;
        }

        /// <summary>
        /// 读取配置下所有节点
        /// </summary>
        public static void ReadAllNode(XElement node, out XNodeC XC)
        {
            XC = null;
            if (node == null)
                return;

            XC = new XNodeC() { LocalName = node.Name.LocalName };

            foreach (XElement C in node.Elements())
            {
                XNodeC xn = null;
                if (C.Elements().Count() > 0)
                    ReadAllNode(C, out xn);
                else
                    xn = new XNodeC { LocalName = C.Name.LocalName, Value = C.Value };

                XC.Elements.Add(xn);
            }

            if (XC.Elements.Count == 0)
                XC.Value = node.Value;
        }
    }
}
